package com.westline.unicom.action;

import java.util.*;

import com.westline.unicom.service.BillService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.LocalizedTextUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import com.westline.unicom.util.ThreeDes;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.*;
public class IndexAction extends BaseAction {
	
	private BillService billService;
	private String sn;
	private String telnum;
	private String teltype;
	private Map bindNumInfo;
	private int isDefault=0;
	private List<Map> bindNumList;
	private Map billInfo;
	private int year;
	private int month;
	private String startToEndStr="";
	private int bindId;
	private List<Map> billInfoList;
	private String mobile;
	private String key = "204121000329819612345678";
	private static Log log = LogFactory.getLog(IndexAction.class);
	public String index(){
		try{
			log.error("出错啦");
		String url=this.getRequest().getQueryString();
		System.out.println("url:@@@@@@@"+url);
		if (url!=null && !url.trim().equals("")){
			url=ThreeDes.decrypt(url, key);
			System.out.println(url);
			String[] parames=url.split("&");
			for (int i=0;i<parames.length;i++){
				String[] pram=parames[i].split("=");
				if (pram[0].equals("sn"))
					sn=pram[1];
				else if (pram[0].equals("mobile")){
					mobile=pram[1];
					String cu = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5-6]))\\d{8}$"; 
					String cum = "^((13[4-9])|(147)|(15[0-2])|(15[7-9])|(170)|(178)|(18[2-4])|(18[7-8]))\\d{8}$"; 
					int flag = 0; 
					System.out.println("check mobile:"+mobile+".");
					if (!mobile.matches(cu)) { 
						//不是联通账号
						if (mobile.matches(cum)) {
							System.out.println(""+mobile+" is mobile");
							return "mobile";
						}
						else{
							System.out.println(""+mobile+" not unicom");
							return "notunicom";
						}
					}
					else{
						System.out.println(""+mobile+" is unicom");
					}
				}				 
			}
		}
		System.out.println("prom  0");
		if (this.getSession().getAttribute("sn")!=null)
			sn=this.getSession().getAttribute("sn").toString();
		this.getSession().setAttribute("sn", sn);
		System.out.println("sn"+sn);
		/*if (this.getSession().getAttribute("bindid")!=null){
			System.out.println("fnid user bindid:"+this.getSession().getAttribute("bindid").toString());
			bindId=Integer.parseInt(this.getSession().getAttribute("bindid").toString());
			bindNumInfo=(Map)billService.getBingNumById(bindId); 
		}else*/
			bindNumInfo=(Map)billService.getDefaultBingNum(sn,mobile); 
		System.out.println("prom  1");
		if (bindNumInfo==null){
			int telType=0;
			try{
			String con[]={mobile,"GUSERPROP"};
			telType=com.westline.unicom.util.DateUtil.getGuserProp(linkSocket(con));
			}catch(Exception e){
				e.printStackTrace();
			}
			if (telType!=0){
			String telInfo[]=null;
			try{
				String con[]=new String[2];
				con[0]=mobile;				
				if (telType==1){
					con[1]="GFEEPOSTPAY";
					telInfo=com.westline.unicom.util.DateUtil.getGfeePostPay(linkSocket(con));
				}
				else if(telType==2){
					con[1]="GFEEPREPAY";
					telInfo=com.westline.unicom.util.DateUtil.getGfeePrePay(linkSocket(con));
				}
				}catch(Exception e){
					e.printStackTrace();
				}
			if (telInfo!=null){				
				billService.insertNumInfo(sn, mobile, 1, 1, telType, telInfo[0], telInfo[1], telInfo[2]);
				bindNumInfo=(Map)billService.getDefaultBingNum(sn,mobile);
		      }
			}else
				return "errornum";
			
		}
		if (bindNumInfo!=null){
			bindNumInfo.put("balance", smaller100(bindNumInfo.get("balance").toString()));
			bindNumInfo.put("realtimecharge", smaller100(bindNumInfo.get("realtimecharge").toString()));
			bindNumInfo.put("arrearage", smaller100(bindNumInfo.get("arrearage").toString()));		
		}
		System.out.println("prom  2"); 
		//发现有默认的绑定账号
		/*int telType=0;
		try{
		String con[]={mobile,"GUSERPROP"};
		telType=com.westline.unicom.util.DateUtil.getGuserProp(linkSocket(con));
		}catch(Exception e){
			e.printStackTrace();
		}*/
		telnum=(String)bindNumInfo.get("bindnumber");
		this.getSession().setAttribute("telnum", telnum);
		int telType=Integer.parseInt(bindNumInfo.get("ispostpay").toString());
		bindId=Integer.parseInt(bindNumInfo.get("id").toString());
		this.getSession().setAttribute("bindid", bindId);
		String telInfo[]=null;
		System.out.println("prom  3");
		try{
			sn=(String)this.getSession().getAttribute("sn");
			String con[]=new String[2];
			con[0]=telnum;
			
			if (telType==1){
				con[1]="GFEEPOSTPAY";
				telInfo=com.westline.unicom.util.DateUtil.getGfeePostPay(linkSocket(con));
			}
			else if(telType==2){
				con[1]="GFEEPREPAY";
				telInfo=com.westline.unicom.util.DateUtil.getGfeePrePay(linkSocket(con));
			}
			
			//更新本地数据库
			if (telInfo!=null){
				System.out.println(telInfo[0]+" @@ "+telInfo[1]+" @@ "+telInfo[2]+" @@ "+telnum+" @@ "+sn);
				billService.reFlashNumInfo(telInfo[0], telInfo[1], telInfo[2], telnum, sn);
				//更新返回值
				bindNumInfo.put("balance", smaller100(telInfo[0]));
				bindNumInfo.put("realtimecharge", smaller100(telInfo[1]));
				bindNumInfo.put("arrearage", smaller100(telInfo[2]));
			}
			}catch(Exception e){
				e.printStackTrace();
			}

			System.out.println("prom  4");
			this.getSession().setAttribute("balance", bindNumInfo.get("balance"));
			this.getSession().setAttribute("realtimecharge",  bindNumInfo.get("realtimecharge"));
			this.getSession().setAttribute("arrearage",  bindNumInfo.get("arrearage"));
			System.out.println("prom over");
		}catch(Exception e){
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public String menuLink(){
		String url=this.getRequest().getQueryString();
		if (url!=null && !url.trim().equals("")){
			url=ThreeDes.decrypt(url, key);
			String[] parames=url.split("&");
			for (int i=0;i<parames.length;i++){
				String[] pram=parames[i].split("=");
				if (pram[0].equals("sn"))
					sn=pram[1];
				else if (pram[0].equals("mobile")){
					mobile=pram[1];
				}				 
			}
		}
		String returnJson="{'status':-1}";
		String cu = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5-6]))\\d{8}$"; 
		int flag = 0; 
		if (!mobile.matches(cu)) { 
			//不是联通账号
			returnJson="{'status':-2}";
		}
		else{
			try{

				System.out.println("beging bindNumInfo loading");
				bindNumInfo=(Map)billService.getDefaultBingNum(sn,mobile); 
				System.out.println("bindNumInfo loading");
			}
			catch(Exception e){
				e.printStackTrace();
			}
		if (bindNumInfo==null){
			//未绑定号码

			System.out.println(" no bindNumInfo load");
			int telType=0;
			try{
			String con[]={mobile,"GUSERPROP"};
			telType=com.westline.unicom.util.DateUtil.getGuserProp(linkSocket(con));
			}catch(Exception e){
				e.printStackTrace();
			}
			if (telType==0){
				returnJson="{'status':-1}";
			}else
			{
			/**
			 * 取余额等信息
			 */
			String telInfo[]=null;
			try{
				String con[]=new String[2];
				con[0]=mobile;
				
				if (telType==1){
					con[1]="GFEEPOSTPAY";
					telInfo=com.westline.unicom.util.DateUtil.getGfeePostPay(linkSocket(con));
				}
				else if(telType==2){
					con[1]="GFEEPREPAY";
					telInfo=com.westline.unicom.util.DateUtil.getGfeePrePay(linkSocket(con));
				}
				}catch(Exception e){
					e.printStackTrace();
				}
			if (telInfo==null){
				//无法取到号码余额信息
				returnJson="{'status':-1}";
			}
			else{
				billService.insertNumInfo(sn, mobile, 1, 1, telType, telInfo[0], telInfo[1], telInfo[2]);
				returnJson="{'status':1,'balance':"+smaller100(telInfo[0])+"}";

				bindNumInfo=(Map)billService.getDefaultBingNum(sn,mobile); 
				bindId=Integer.parseInt(bindNumInfo.get("id").toString());
				this.getRequest().setAttribute("bindid", bindId);
			}
			}
		}else{
		//发现有默认的绑定账号
			System.out.println("bindNumInfo load");
			returnJson="{'status':2,'balance':"+smaller100(bindNumInfo.get("balance").toString())+"}";
		telnum=(String)bindNumInfo.get("bindnumber");
		int telType=Integer.parseInt(bindNumInfo.get("ispostpay").toString());
		bindId=Integer.parseInt(bindNumInfo.get("id").toString());
		this.getRequest().setAttribute("bindid", bindId);
		String telInfo[]=null;
		try{
			
			String con[]=new String[2];
			con[0]=telnum;
			
			if (telType==1){
				con[1]="GFEEPOSTPAY";
				telInfo=com.westline.unicom.util.DateUtil.getGfeePostPay(linkSocket(con));
			}
			else if(telType==2){
				con[1]="GFEEPREPAY";
				telInfo=com.westline.unicom.util.DateUtil.getGfeePrePay(linkSocket(con));
			}
			//更新本地数据库
			//10345  141952545248200000000GFEEPOSTPAY 18602533128         GA0000CHQZ00000251    132105Call service failed!Call time is full 
			if (telInfo!=null){
			billService.reFlashNumInfo(telInfo[0], telInfo[1], telInfo[2], telnum, sn);
			//更新返回值
			bindNumInfo.put("balance", smaller100(telInfo[0]));
			bindNumInfo.put("realtimecharge", smaller100(telInfo[1]));
			bindNumInfo.put("arrearage", smaller100(telInfo[2]));
			returnJson="{'status':1,'balance':"+smaller100(telInfo[0])+"}";
			}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		}
			this.getSession().setAttribute("returnJson", returnJson);
		return SUCCESS;
	}
	public String bindNumManager(){
		sn=(String)this.getSession().getAttribute("sn");
		bindNumList=billService.getBingNumList(sn);
		return SUCCESS;
	}
	public String changeBindNum(){
		sn=(String)this.getSession().getAttribute("sn");
		bindNumList=billService.getBingNumList(sn);
		return SUCCESS;
	}
	public String ajaxChangeBindNum(){
		JSONObject jsonObject  = new JSONObject();
		try{
			bindNumInfo=(Map)billService.getBingNumById(bindId); 
			telnum=(String)bindNumInfo.get("bindnumber");
			this.getSession().setAttribute("telnum", telnum);
			this.getSession().setAttribute("bindid", bindId);
			this.getSession().setAttribute("balance", bindNumInfo.get("balance"));
			this.getSession().setAttribute("realtimecharge",  bindNumInfo.get("realtimecharge"));
			this.getSession().setAttribute("arrearage",  bindNumInfo.get("arrearage"));
			jsonObject.put("status", "ok");
			this.print(jsonObject.toString());
		}
		catch(Exception e){
			e.printStackTrace();
			jsonObject.put("status", "err");
			this.print(jsonObject.toString());
		}
		return null;
	}
	public String nowMonthBill(){
		telnum=(String)this.getSession().getAttribute("telnum");
		//int bindId=Integer.parseInt(this.getSession().getAttribute("bindid").toString());
		Date dat=new Date();
		int nowYear=dat.getYear()+1900;
		int nowMonth=dat.getMonth()+1;
		String s_month=""+nowMonth;
		if (nowMonth<10)
			s_month="0"+nowMonth;
		billInfoList=(List<Map>)billService.getBillHistoryInfo(bindId, nowYear, nowMonth);
		String con[]={telnum,"102011201001",nowYear+""+s_month};
		try{
			String sst=linkSocket(con);
			System.out.println(sst);
			//String s="101113 14199607238520000000110201120100118602533128         GA0000CHQZ00000251    100000增值业务费:10.30;--代收费:5.00;--短消息费:5.30;--手机邮箱包月费:0.00;月固定费:126.00;--GPRSWAP月租费:30.00;--来电显示费:0.00;--3G包月费:96.00;消费合计:136.30;抵扣合计:0.00;实际应缴合计:136.30;";
			
			List<Map> billinfoList=com.westline.unicom.util.DateUtil.getHistoryBill2(sst);
			System.out.println(billinfoList.size());
			if (billinfoList!=null){
				if (billInfoList==null || billInfoList.size()==0){
					System.out.println("insert");
					billService.insertBillHistoryInfo(bindId, nowYear, nowMonth, billinfoList);
				
				}else{
					billService.reFlashBillHistoryInfo(bindId, nowYear, nowMonth, billinfoList);
				
				}
				billInfoList=(List<Map>)billService.getBillHistoryInfo(bindId, nowYear, nowMonth);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		 
		return SUCCESS;
	}
	/**
	 * 历史账单
	 * @return
	 */
	public String lastMonthBill(){
		telnum=(String)this.getSession().getAttribute("telnum");
		//int bindId=Integer.parseInt(this.getSession().getAttribute("bindid").toString());
		Date dat=new Date();
		int nowYear=dat.getYear()+1900;
		int nowMonth=dat.getMonth()+1;
		int lastMonthYear=nowYear;
		int lastMonth=nowMonth-1;
		if (nowMonth==1){
			lastMonthYear--;
			lastMonth=12;
		}
			
		List<Map> monthList=new ArrayList<Map>();
		if (nowMonth>5){
			for (int i=1;i<=5;i++){
				Map mp=new HashMap();
				mp.put("year", nowYear);
				mp.put("month", nowMonth-i);
				monthList.add(mp);
			}			
		}else{
			for (int i=nowMonth;i>1;i--){
				Map mp=new HashMap();
				mp.put("year", nowYear);
				mp.put("month", i-1);
				monthList.add(mp);
			}
			nowYear--;
			for (int i=0;i<=(5-nowMonth);i++){
				Map mp=new HashMap();
				mp.put("year", nowYear);
				mp.put("month", 12-i);
				monthList.add(mp);
			}
			
		}
		this.getSession().setAttribute("monthList", monthList);
		if (year==0)
			year=lastMonthYear;
		if (month==0)
			month=lastMonth;
		if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
			startToEndStr=year+" 年 "+month+" 月 1 日 -- "+year+" 年 "+month+" 月 31 日";
		if (month==4 || month==6 || month==9 || month==11)
			startToEndStr=year+" 年 "+month+" 月 1 日 -- "+year+" 年 "+month+" 月 30 日";
		if (month==2)
			startToEndStr=year+" 年 "+month+" 月 1 日 -- "+year+" 年 "+month+" 月 29 日";
		billInfoList=(List<Map>)billService.getBillHistoryInfo(bindId, year, month);
		String monthStr=year+""+month;
		if (month<10)
			monthStr=year+"0"+month;
		String con[]={telnum,"102011201001",monthStr};
		try{
			String sst=linkSocket(con);
			System.out.println(sst);
			List<Map> billinfoList=com.westline.unicom.util.DateUtil.getHistoryBill2(sst);
			System.out.println(billinfoList.size());
			if (billinfoList!=null){
				if (billInfoList==null || billInfoList.size()==0){
					System.out.println("insert");
					billService.insertBillHistoryInfo(bindId, year, month, billinfoList);
				
				}else{
					billService.reFlashBillHistoryInfo(bindId, year, month, billinfoList);
				
				}
				billInfoList=(List<Map>)billService.getBillHistoryInfo(bindId, year, month);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		 
		return SUCCESS;
	}
	public String bindNumShow(){
		if (this.getSession().getAttribute("sn")!=null)
			sn=this.getSession().getAttribute("sn").toString();
			bindNumInfo=(Map)billService.getDefaultBingNum(sn); 
		if (bindNumInfo==null){
			isDefault=1;
		}		 
		return SUCCESS;
	}
	
	public String ajaxBindNum(){
		JSONObject jsonObject  = new JSONObject();
		try{
			/**
			 * 验证号码是后付费还是预付费
			 * 0失败  1后付费  2：预付费
			 */
			System.out.println("begin");
			int telType=0;
			try{
			String con[]={telnum,"GUSERPROP"};
			telType=com.westline.unicom.util.DateUtil.getGuserProp(linkSocket(con));
			}catch(Exception e){
				e.printStackTrace();
			}
			if (telType==0){
				jsonObject.put("status", "telerr");
				this.print(jsonObject.toString());
				return null;
			}
			System.out.println(telType);
			/**
			 * 取余额等信息
			 */
			String telInfo[]=null;
			try{
				sn=(String)this.getSession().getAttribute("sn");
				String con[]=new String[2];
				con[0]=telnum;
				
				if (telType==1){
					con[1]="GFEEPOSTPAY";
					telInfo=com.westline.unicom.util.DateUtil.getGfeePostPay(linkSocket(con));
				}
				else if(telType==2){
					con[1]="GFEEPREPAY";
					telInfo=com.westline.unicom.util.DateUtil.getGfeePrePay(linkSocket(con));
				}
				}catch(Exception e){
					e.printStackTrace();
				}
			if (telInfo==null){
				//无法取到号码余额信息
				jsonObject.put("status", "yueeerr");
				this.print(jsonObject.toString());
				return null;
			}
			System.out.println(telInfo[0]);
			billService.insertNumInfo(sn, telnum, isDefault, 1, telType, telInfo[0], telInfo[1], telInfo[2]);
			jsonObject.put("status", "ok");
		}
		catch(Exception e){
			jsonObject.put("status", "err");
			e.printStackTrace();
		}
		this.print(jsonObject.toString());
		return null;
	}
	public String modifyBindNumShow(){		
			bindNumInfo=(Map)billService.getBingNumById(bindId); 
		return SUCCESS;
	}
	
	public String ajaxUpdateBindNum(){
		JSONObject jsonObject  = new JSONObject();
		try{
			/**
			 * 验证号码是后付费还是预付费
			 * 0失败  1后付费  2：预付费
			 */
			System.out.println("begin");
			int telType=0;
			try{
			String con[]={telnum,"GUSERPROP"};
			telType=com.westline.unicom.util.DateUtil.getGuserProp(linkSocket(con));
			}catch(Exception e){
				e.printStackTrace();
			}
			
			System.out.println(telType);
			/**
			 * 取余额等信息
			 */
			String telInfo[]=null;
			try{
				sn=(String)this.getSession().getAttribute("sn");
				String con[]=new String[2];
				con[0]=telnum;
				
				if (telType==1){
					con[1]="GFEEPOSTPAY";
					telInfo=com.westline.unicom.util.DateUtil.getGfeePostPay(linkSocket(con));
				}
				else if(telType==2){
					con[1]="GFEEPREPAY";
					telInfo=com.westline.unicom.util.DateUtil.getGfeePrePay(linkSocket(con));
				}
				}catch(Exception e){
					e.printStackTrace();
				}
			if (telInfo==null){
				//无法取到号码余额信息
				jsonObject.put("status", "yueeerr");
				this.print(jsonObject.toString());
				return null;
			}
			System.out.println(telInfo[0]);
			billService.updateNumInfo(sn,bindId, telnum, isDefault, 1, telType, telInfo[0], telInfo[1], telInfo[2]);
			jsonObject.put("status", "ok");
		}
		catch(Exception e){
			jsonObject.put("status", "err");
			e.printStackTrace();
		}
		this.print(jsonObject.toString());
		return null;
	}
	public String ajaxRemoveBindNum(){
		JSONObject jsonObject  = new JSONObject();		
		try{
			billService.removeNumInfo(bindId);
			jsonObject.put("status", "ok");
		}
		catch(Exception e){
			jsonObject.put("status", "err");
			e.printStackTrace();
		}
		this.print(jsonObject.toString());
		return null;
	}
	public BillService getBillService() {
		return billService;
	}

	public void setBillService(BillService billService) {
		this.billService = billService;
	}
	public String getSn() {
		return sn;
	}
	public void setSn(String sn) {
		this.sn = sn;
	}
	public String getTelnum() {
		return telnum;
	}
	public void setTelnum(String telnum) {
		this.telnum = telnum;
	}
	public String getTeltype() {
		return teltype;
	}
	public void setTeltype(String teltype) {
		this.teltype = teltype;
	}
	public String linkSocket(String[] con){
		String host = "10.101.2.44";
        int port = Integer.parseInt("10999");
        String returns=null;
        try
        {
        	 String conn="";
             if (con.length==2)
             	conn=con[0]+";"+con[1];
             else
             	conn=con[0]+";"+con[1]+";"+con[2];
            Socket socket = new Socket(host, port);
            socket.setSoTimeout(10000);
            InputStream in = (InputStream) socket.getInputStream();
            PrintWriter out =  new  PrintWriter(socket.getOutputStream());
           
            out.println(conn);
            out.flush();
            InputStreamReader inSR = new InputStreamReader(in,"gb2312");  
            BufferedReader br = new BufferedReader(inSR);  
            returns=br.readLine();
            in.close();
            out.close();
            socket.close();
        }
        catch (UnknownHostException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
		return returns;
	}
	/*
	 * 将数字型字符串缩小100倍
	 */
	public String smaller100(String st){
		if (st==null || st.equals(""))
			return "0.00";
		try{
			Integer.parseInt(st);			
		}catch(Exception e){
			return "0.00";
		}
		if (st.length()==1){
			return "0.0"+st;
		}else if (st.length()==2){
			return "0."+st;
		}else {
			return st.substring(0,st.length()-2)+"."+st.substring(st.length()-2,st.length());
		}
	}
	public Map getBindNumInfo() {
		return bindNumInfo;
	}
	public void setBindNumInfo(Map bindNumInfo) {
		this.bindNumInfo = bindNumInfo;
	}
	public int getIsDefault() {
		return isDefault;
	}
	public void setIsDefault(int isDefault) {
		this.isDefault = isDefault;
	}
	public List<Map> getBindNumList() {
		return bindNumList;
	}
	public void setBindNumList(List<Map> bindNumList) {
		this.bindNumList = bindNumList;
	}

	public Map getBillInfo() {
		return billInfo;
	}

	public void setBillInfo(Map billInfo) {
		this.billInfo = billInfo;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public String getStartToEndStr() {
		return startToEndStr;
	}

	public void setStartToEndStr(String startToEndStr) {
		this.startToEndStr = startToEndStr;
	}

	public int getBindId() {
		return bindId;
	}

	public void setBindId(int bindId) {
		this.bindId = bindId;
	}

	public List<Map> getBillInfoList() {
		return billInfoList;
	}

	public void setBillInfoList(List<Map> billInfoList) {
		this.billInfoList = billInfoList;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	
}
